import 'dart:async';

import 'package:cgg_tools_flutter/http/request.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';

class RegisterPage extends StatefulWidget {
  const RegisterPage({super.key});

  @override
  State<RegisterPage> createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  bool isButtonEnable = true; //按钮状态  是否可点击
  String buttonText = '发送验证码'; //初始文本
  int count = 60; //初始倒计时时间
  Timer? timer; //倒计时的计时器
  TextEditingController mController = TextEditingController();

  // 提交
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey<FormState> _phoneFormKey = GlobalKey<FormState>();
  String _phone = '18007496225';
  String _pw = '';
  String _code = '';

  // 密码显示、隐藏
  bool _isObscure = true;
  Color _eyeColor = Colors.grey;

  void _buttonClickListen() async {
    if (isButtonEnable) {
      //当按钮可点击时
      final form = _phoneFormKey.currentState;
      if (form!.validate()) {
        form.save();
        Result result = await sendRegisterVerificationCode(_phone);
        if (result.code != 200) {
          print('发送验证码失败');
          return null;
        }
        // 验证码发送成功
        isButtonEnable = false; //按钮状态标记
        _initTimer();
        return null; //返回null按钮禁止点击
      }
    }
    return null;
  }

  void _initTimer() {
    timer = Timer.periodic(Duration(seconds: 1), (Timer t) {
      count--;
      setState(() {
        if (count == 0) {
          t.cancel(); //倒计时结束取消定时器
          isButtonEnable = true; //按钮可点击
          count = 60; //重置时间
          buttonText = '发送验证码'; //重置按钮文本
        } else {
          buttonText = '$count后重新发送'; //更新文本内容
        }
      });
    });
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    timer?.cancel(); //销毁计时器
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final phone = TextFormField(
      keyboardType: TextInputType.number,
      autofocus: false,
      initialValue: _phone,
      onSaved: (val) => _phone = val!,
      validator: (value) {
        RegExp reg = RegExp(r'^1{1}\d{10}$');
        if (!reg.hasMatch(value!)) {
          return '请输入正确的手机号码';
        } else {
          return null;
        }
      },
      decoration: InputDecoration(
        hintText: '手机号',
        contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
        border: OutlineInputBorder(borderRadius: BorderRadius.circular(32.0)),
      ),
    );

    final password = TextFormField(
      autofocus: false,
      initialValue: '',
      onSaved: (val) => _pw = val!,
      obscureText: _isObscure,
      validator: (value) {
        if (value!.length < 6 || value.length > 16) {
          return '密码在6-16位数之间哦';
        } else {
          return null;
        }
      },
      decoration: InputDecoration(
        hintText: '密码',
        contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
        border: OutlineInputBorder(borderRadius: BorderRadius.circular(32.0)),
        suffixIcon: IconButton(
          icon: Icon(Icons.remove_red_eye, color: _eyeColor),
          onPressed: () {
            setState(() {
              _isObscure = !_isObscure;
              _eyeColor = (_isObscure ? Colors.grey : Theme.of(context).iconTheme.color)!;
            });
          },
        ),
      ),
    );

    onsubmit() async {
      final form = _formKey.currentState;
      final phoneform = _phoneFormKey.currentState;

      if (phoneform!.validate() && form!.validate()) {
        form.save();
        phoneform.save();
        print('注册中');
        print(_phone);
        print(_pw);
        Result result = await registerUser({
          "phone": _phone,
          "pass": _pw,
          "code": _code,
        });
        if (result.code != 200) {
          print('注册异常');
          return;
        }
        // 注册成功 转跳到登陆页面
        context.go('/login');
      }
    }

    return Container(
      child: Scaffold(
        appBar: AppBar(title: Text('注册')),
        body: Form(
          key: _formKey,
          child: Container(
            padding: EdgeInsets.only(left: 24.0, right: 24.0),
            child: Column(
              children: <Widget>[
                Container(height: 200),
                Container(
                  color: Colors.white,
                  child: Form(key: _phoneFormKey, child: phone),
                ),
                Container(
                  color: Colors.white,
                  padding: EdgeInsets.only(top: 10, bottom: 10),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.baseline,
                    textBaseline: TextBaseline.ideographic,
                    children: <Widget>[
                      Expanded(
                        child: TextFormField(
                          keyboardType: TextInputType.number,
                          onSaved: (value) => _code = value!,
                          validator: (value) {
                            if (value?.length != 6) {
                              return '验证码是6位数';
                            }
                            return null;
                          },
                          controller: mController,
                          textAlign: TextAlign.left,
                          decoration: InputDecoration(
                            hintText: ('填写验证码'),
                            contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
                            hintStyle: TextStyle(color: Color(0xff999999), fontSize: 13),
                            alignLabelWithHint: true,
                            border: OutlineInputBorder(borderRadius: BorderRadius.circular(32.0)),
                          ),
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.only(left: 20),
                        width: 150,
                        child: ElevatedButton(
                          onPressed: _buttonClickListen,
                          child: Text(buttonText, style: TextStyle(fontSize: 13)),
                        ),
                      ),
                    ],
                  ),
                ),
                password,
                Container(
                  width: double.infinity,
                  height: 45,
                  margin: EdgeInsets.only(top: 50),
                  child: ElevatedButton(
                    onPressed: onsubmit,
                    child: Text('注册', style: TextStyle(color: Colors.white, fontSize: 15)),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
